<template>
  <eui-background type="common">
    <eui-navbar ref="EuiNavBar" :title="title" :storeName="sUserStoreName" :storeId="sUserStore" displayable="true" />
    <view class="top-view" v-if="mainData.c_status === '0'">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码" leftIcon="icon-saoyisao"
                      @confirm="searchConfirm"  @leftIconClick="clickScanRight" radius="30" maxlength="30">
      </eui-search-bar>
    </view>
    <eui-card hPadding="28">
      <eui-card-input v-model="mainData.c_adno" title="部门" h-padding="0" type="textname2" :name="getName('rdsDeparts', mainData.c_adno)"
                      ref="cardAdnoInput" isBlur alignType="left" required="true" :rightIconType="detailData.length > 0 ? '' : 'right'"
                      @iconClick="clickRight('c_adno')" @confirm="validateMain('c_adno', mainData.c_adno)" />
      <eui-card-input v-model="mainData.c_wno" title="仓库"  h-padding="0" type="textname2" :name="getName('rdsWnos', mainData.c_wno)"
                      ref="cardWnoInput" isBlur alignType="left" required="true" :rightIconType="detailData.length > 0 ? '' : 'right'"
                      @iconClick="clickRight('c_wno')" @confirm="validateMain('c_wno', mainData.c_wno)"/>
      <eui-card-input v-model="mainData.c_req_priv" title="补货权限" :range="privSelectList" hPadding="0" alignType="left"
                      ref="cardReqPrivInput" type="radio" :displayable="detailData.length > 0" rightIconType="right" @buttonClick="changePriv" />
      <eui-card-input v-model="mainData.c_req_fast" title="补货时效" :range="fastSelectList" hPadding="0" alignType="left"
                      ref="cardReqFastInput" type="radio" :displayable="detailData.length > 0" rightIconType="right" @buttonClick="changeFast" />
      <eui-card-input v-model="mainData.c_expect_dt" title="期望送货日期" placeholder="请选择日期" hPadding="0" alignType="left" @input="effectDaChanged"
                      v-if="mainData.c_req_priv === '1' || mainData.c_req_fast === '1'"
                      type="date" :displayable="detailData.length > 0" :rightIconType="detailData.length === 0 ? 'right' : ''" />
      <view class="item-view">
        <eui-text type="name2" title="已录品种数" :value="c_sku_rec + ''"/>
        <eui-text type="name2" title="已录总数量" :value="c_n_rec + ''"/>
      </view>
    </eui-card>
    <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
      <scroll-view scroll-y="true" style="height: 100%;">
        <view style="display:flex;flex-direction: column">
          <eui-card hPadding="28" v-if="detailData && detailData.length > 0">
            <eui-swipe-action>
              <view :ref="'dataItem' + index" v-for="(item, index) in detailData" :key="index" @click="onClickGdsInfo(item, index)">
                <eui-swipe-actionitem :ref="`swipeActionItem${index}`" :right-options="options" show="none" :auto-close="true"
                                      @change="change" @click="bindClick($event, index)" :disabled="mainData.c_status != '0'">
                  <view class="item-view">
                    <eui-text type="name2" :value="index + 1 + '. ' + '[' + item.c_gcode + ']' + item.c_gname" cWidth="width: 100%" />
                    <eui-text type="name2" :value="item.c_barcode" title="主条码" />
                    <eui-text type="slash2" :value="item.c_req_pack" :name="item.c_req_unit" title="包装/单位"/>
                    <eui-text type="price2" title="门店库存" :value="item.c_n_inv" :valueStyle="showRightStyle" :precision="3" />
                    <eui-text type="price2" title="配送中心库存" :value="item.c_n_inv_dc" :valueStyle="showRightStyle" :precision="3" v-if="item.c_d_type != '1'" />
                    <eui-text type="price2" title="售价" :value="item.c_price" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="售价金额" :value="item.c_at_sale" :valueStyle="showRightStyle"/>
                    <eui-text v-if="sysConfig.inputType === '1'" type="price2" title="申请件数" :value="item.c_n_pack" :valueStyle="showRightStyle"/>
                    <eui-text v-if="sysConfig.inputType === '1'" type="price2" title="申请零数" :value="item.c_n_odd" :valueStyle="showRightStyle" :precision="3"/>
                    <eui-text v-if="sysConfig.inputType === '2'" type="price2" title="申请包装数" :value="item.c_n_input" :valueStyle="showRightStyle" :precision="3"/>
                    <eui-text type="price2" title="申请数量" :value="item.c_n" :valueStyle="showRedStyle" :precision="3"/>
                    <eui-text v-model="JSON.parse(item.c_err_msg)[0].c_msg_err" type="name2" v-if="item.c_err_msg"
                              title="错误:" cWidth="width: 100%;margin: 10rpx 0 10rpx 0" valueStyle="color: #FF4000;" />
                  </view>
                </eui-swipe-actionitem>
              </view>
            </eui-swipe-action>
          </eui-card>
        </view>
      </scroll-view>
    </view>
    <view class="bottom-view">
      <view class="center-style">
        <eui-button type="max2" title="保存" singleTag="保存" @buttonClick="buttonClick"
                    :disabled="!(mainData.c_status == '0' && detailData.length > 0)"/>
        <view class="gap-view" />
        <eui-button type="max" title="审核" singleTag="审核" @buttonClick="buttonClick"
                    :disabled="!(mainData.c_status == '0' && detailData.length > 0)"/>
      </view>
    </view>
    <eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :mask-click="false">
      <view class="popup-content">
        <view style="padding: 20rpx 20rpx 0 20rpx">
          <view class="item-view">
            <eui-text :value="'[' + currentGds.c_gcode + ']' + currentGds.c_gname" type="name2"
                      title="商品" cWidth="width: 100%" />
            <eui-text :value="getName('rdsProviders', currentGds.c_provider)" type="name2" title="供应商" cWidth="width: 100%" />
            <eui-text v-model="currentGds.c_barcode" type="name2" title="主条码" />
            <eui-text :value="currentGds.c_req_pack" :name="currentGds.c_req_unit" type="slash2"
                      title="包装/单位" />
            <eui-text :value="getDictName('拆零标志', currentGds.c_unpack)" type="name2" title="拆零标志" />
            <eui-text :value="currentGds.c_n_inv" type="price2" title="门店库存" :valueStyle="showRightStyle" :precision=3 />
            <eui-text :value="currentGds.c_n_inv_dc" type="price2" title="配送中心库存" :valueStyle="showRightStyle" :precision=3
                      v-if="currentGds.c_d_type != '1'" />
            <eui-text :value="currentGds.c_n_onway_in" type="price2" title="入库在途数量" :valueStyle="showRightStyle" :precision=3 />
            <eui-text :value="currentGds.c_price" type="price2" title="售价" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_at_sale" type="price2" title="售价金额" :valueStyle="showRightStyle"/>
            <eui-text :value="currentGds.c_n" type="price2" title="申请数量" :valueStyle="showRightStyle" :precision=3 />
          </view>
          <view class="item-view" v-if="mainData.c_status != '0'">
            <eui-text :value="getDictName('物流模式', currentGds.c_d_type)" type="name2" title="物流模式" />
            <eui-text :value="getDictName('越库类型', currentGds.c_s_mode)" type="name2" title="越库类型" />
            <eui-text v-model="currentGds.c_dc_store_id" type="titlename2" title="配送中心"
                      :name="getRelatedName('rdsStores', currentGds.c_dc_store_id)" />
            <eui-text v-model="currentGds.c_wno" type="titlename2" title="目的仓库"
                      :name="getRelatedName('rdsWnos', currentGds.c_wno)" />
            <eui-text v-if="sysConfig.inputType === '1'" :value="currentGds.c_n_pack" type="price2" title="申请件数" :required="true" :valueStyle="showRightStyle"/>
            <eui-text v-if="sysConfig.inputType === '1'" :value="currentGds.c_n_odd" type="price2" title="申请零数" :required="true" :valueStyle="showRightStyle" :precision=3 />
            <eui-text v-if="sysConfig.inputType === '2'" :value="currentGds.c_n_input" type="price2" title="申请包装数" :required="true" :valueStyle="showRightStyle" :precision=3 />
            <eui-text v-model="currentGds.c_note" type="name2" title="备注"
                      cWidth="width: 100%; margin-bottom: 20rpx" :valueStyle="noteStyle"/>
          </view>
          <view v-if="mainData.c_status == '0'">
            <eui-card-input v-model="currentGds.c_d_type" title="物流模式" :range="dTypeSelectList" h-padding="0" alignType="left"
                            type="radio" :displayable="mainData.c_req_priv != '1'" rightIconType="right" @buttonClick="dTypeInput" />
            <eui-card-input v-model="currentGds.c_s_mode" title="越库类型" :range="sModeSelectList" h-padding="0" alignType="left"
                            type="radio" :displayable="currentGds.c_d_type != '2'" rightIconType="right" />
            <eui-card-input v-model="currentGds.c_dc_store_id" title="配送中心" type="selector" h-padding="0"
                            :range="dcStoreSelectList" alignType="left" :displayable="['', '1'].includes(currentGds.c_d_type)"
                            :required="!['', '1'].includes(currentGds.c_d_type)" placement="top" placeholder=""
                            :rightIconType="['', '1'].includes(currentGds.c_d_type) ? '' : 'right'" />
            <eui-card-input v-model="currentGds.c_wno" title="目的仓库"  h-padding="0" type="textname2" :name="getName('rdsWnos', currentGds.c_wno)"
                            ref="cardAdnoGoodsInput" alignType="left" rightIconType="right"
                            @iconClick="goodsClickRight" @confirm="validateMain('c_wno', currentGds.c_wno)" isBlur />
            <eui-card-input v-if="sysConfig.inputType === '1'" v-model="currentGds.c_n_pack" type="number" title="申请件数" :required="true" h-padding="0"
                            fieldName="c_n_pack" @confirm="validateDetail" isBlur ref="cardNPackInput"
                            placeholder="请输入件数" maxlength="9" alignType="left" />
            <eui-card-input v-if="sysConfig.inputType === '1'" v-model="currentGds.c_n_odd" type="number" title="申请零数" :required="true" h-padding="0"
                            fieldName="c_n_odd" @confirm="validateDetail" isBlur ref="cardNOddInput"
                            placeholder="请输入零数" maxlength="9" alignType="left" />
            <eui-card-input v-if="sysConfig.inputType === '2'" v-model="currentGds.c_n_input" type="number" title="包装数" :required="true" h-padding="0"
                            fieldName="c_n_input" @confirm="validateDetail" isBlur ref="cardNIptInput"
                            placeholder="请输入包装数" maxlength="9" alignType="left" />
            <eui-card-input v-model="currentGds.c_note" title="备注" fieldName="c_note" h-padding="0"
                            maxlength="100" alignType="left" />
          </view>
        </view>
        <view class="popup-bottom flex-1 flex">
          <eui-button type="max2" title="关闭" singleTag="关闭" @buttonClick="buttonClick"></eui-button>
          <eui-button type="max" title="确认" singleTag="确认" @buttonClick="buttonClick" :disabled="mainData.c_status != '0'"></eui-button>
        </view>
      </view>
    </eui-popup>
  </eui-background>
</template>

<script setup type="ts">
import {onMounted, ref, reactive} from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { validateStores, validateGds, defaultMapping, validateStoresAndWno  } from '@/hooks/useValidateMethod';
import { todayAdd, formatNow } from '@/hooks/useUtils';
import service from "@/common/service";
import {getRdsUrl, rdsRequest, rdsRequestAsync} from '@/hooks/rdsServices';
import { calcAtInByPt, validateOddLot, round, calcPtInByPtPay, calcPetpayByPtPay } from '@/hooks/useCalculateMethod';
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { getRelatedName, getDictName, getUserDictSelectList, getDictSelect, getDictSelectList, getWeightUnits } from '../components/RelatedName.js';
import { init, getRdsUserDepartAuthority, getRdsSysConfig } from '@/hooks/init';
import dateRangUtil from "@/common/dateRangUtil";
import { validateAdnoLevel } from '@/hooks/useBillInfo';
import Enjoy from "@/common/enjoy";
import { getDcStoreInfo } from '@/hooks/useDcStoreInfo';

const rdsUrl = getRdsUrl();
const isOpened = ref('none');
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const listHeight = ref(300);
const oriHeight = ref(300);
const noteStyle = ref('white-space: nowrap;overflow: hidden;text-overflow: ellipsis');
const c_id = ref(''); //单据号
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const isCurrentGds = ref([]);
const title = ref('补货申请');
const c_sku_rec = ref(0);  //已录品种数
const c_n_rec = ref(0);  //已录总数量
const height = ref(0);
const width = ref(0);
const c_disabled = ref(false);
const c_status = ref('0');
const c_gcode = ref('');
const searchText = ref('');
const selectType = ref('');
const options = ref([{
  text: '删除',
  style: {
    backgroundColor: '#F56C6C',
  }
}]);
const showRightStyle = ref('text-align: right');
const showRedStyle = ref('text-align: right;color: #FF4000;');
const sysConfig = ref({
  isBarcode: 0, // 0-否 1-是，默认为否，是：启用时则支持按箱码订货，否则不支持按箱码订货
  isStrict: '2',//0-不控制，1-严格控制，2-提示但不控制
  inputType: '1' // 1-件数零数分别录入方式 2-自动识别含量单值录入方式
});
const uniFabContent = ref( [
  {
    text: '删除单据'
  },
]);
const dcStoreSelectList = ref([]);
const privSelectList = ref([]);
const fastSelectList = ref([]);
const dTypeSelectList = ref([]);
const sModeSelectList = ref([]);
const detailData = ref([]);
const listManager = ref([]);
let delList = reactive([]);
let newList = reactive([]);
let modifiedList = reactive([]);
const currentGds = ref({});
const currentGdsIndex = ref(0);
const mainData = ref({
  c_tenant_id: '',
  c_id: '',
  c_bill_type: '501',
  c_status: '0',
  c_mk_type: '3',
  c_gmode: '',
  c_property_group: '',
  c_pal_kind: '1',//进货损溢
  c_pal_flag: '1',//报损
  c_store_id: sUserStore.value,
  c_store_name: sUserStoreName.value,
  c_rec_store_type: '',
  c_wno: '00',
  c_wname: '本部',
  c_adno: '',
  c_org_no: '',
  c_req_userno: sUserStore.value,
  c_charge_userno: '',
  c_send_wms: '',
  c_send_wms_dt: null,
  c_n_l: 0,
  c_at_pay_l: 0,
  c_aet_pay_l: 0,
  c_at_cost_l: 0,
  c_aet_cost_l: 0,
  c_at_sale_l: 0,
  c_mk_store_id: sUserStore.value,
  c_mk_store_name: sUserStoreName.value,
  c_mk_dt: dateRangUtil.formatDate(new Date(),'YYYY-MM-DD HH:mm:ss'),
  c_mk_userno: sUser.value,
  c_approve_status: '1',
  c_approve_dt: null,
  c_au_dt: null,
  c_au_userno: '',
  c_void_dt: null,
  c_void_userno: '',
  c_print_dt: null,
  c_print_userno: '',
  c_print_n: 0,
  c_orig_id: '',
  c_orig_type: '',
  c_src_id: '',
  c_src_type: '',
  c_note: '',
  c_sys_note: '',
  c_n_p: 0,
  c_at_pay_p: 0,
  c_aet_pay_p: 0,
  c_at_cost_p: 0,
  c_aet_cost_p: 0,
  c_at_sale_p: 0,
  c_req_priv: '0',
  c_req_fast: '0',
  c_expect_dt: null,
});
const currentPage = ref(1);
const btnSaveEnabled = ref(true);
const gdsPopup = ref(null);
const RdsSearchBar = ref(null);
const cardNOddInput = ref(null);
const cardNIptInput = ref(null);
const cardNPackInput = ref(null);
const isGoods = ref(false);

onMounted(() => {
  getListHeight()
})

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        let finalHeight = height / (res.windowWidth / 750) - 100;
        listHeight.value = finalHeight;
        oriHeight.value = finalHeight;
      }).exec()
    }
  });
};

const changePriv = (e) => {
  mainData.value.c_req_priv = e;
  if (e === '1' || mainData.value.c_req_fast === '1') {
    listHeight.value = oriHeight.value - 89
  } else {
    listHeight.value = oriHeight.value;
    mainData.value.c_expect_dt = null
  }
};

const changeFast = (e) => {
  if (mainData.value.c_req_priv === '1' || e === '1') {
    listHeight.value = oriHeight.value - 89;
  } else {
    listHeight.value = oriHeight.value;
    mainData.value.c_expect_dt = null
  }
};

onLoad(async (option) => {
  const result = await validateStores(
      { fieldName: 'c_store_id', row: {}, newValue: option.storeId },
      { ischecklimit: true, firstValueMode: true }
  );
  if (['2', '3'].includes(result?.c_type)) {
    await setDefault({
      sUserStore: result.c_id,
      sUserStoreName: result.c_sname
    });
    sUserStore.value = option.storeId;
    c_id.value = option.c_id;
    mainData.value.c_id = option.c_id;
    c_gcode.value = option.c_gcode;
    if (option.c_id) {
      title.value = option.c_id + '详情'
      service.enjoyShowLoading("正在加载...")
      await billQuery();
      service.enjoyHideLoading();
    }
    dcStoreSelectList.value = await getDcStoreInfo();
    privSelectList.value = getDictSelectList('补货权限');
    fastSelectList.value = getDictSelectList('补货时效');
    dTypeSelectList.value = getDictSelectList('物流模式');
    sModeSelectList.value = getDictSelectList('越库类型');
  } else {
    setTimeout(() => {
      clickRight('c_store_id')
    }, 1000);
  }
  await getSysConfig();
})

const setDefault = async (storeInfo) => {
  const { loginInfo } = mainStore;
  sUserStore.value = storeInfo?.sUserStore || loginInfo.sUserStore;
  sUserStoreName.value = storeInfo?.sUserStoreName || loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
  mainData.value.c_store_id = storeInfo?.sUserStore || loginInfo.sUserStore;
  mainData.value.c_mk_store_id = storeInfo?.sUserStore || loginInfo.sUserStore;
  mainData.value.c_mk_userno = loginInfo.sUser;
  //验证部门层级
  if (!c_id.value) {
    if (!loginInfo.sCurrentAdno) {
      return;
    }
    const result = await validateAdnoLevel({ IuputData: loginInfo.sCurrentAdno, billKind: "50", tenantId: loginInfo.idsToken.tenantid });
    if (result && !result.HasException) {
      const userAdno = await getRdsUserDepartAuthority();
      if (userAdno.includes(loginInfo.sCurrentAdno)) {
        mainData.value.c_adno = loginInfo.sCurrentAdno;
      }
    }
  }
}

const getSysConfig = async () => {
  sysConfig.value.isBarcode = await getRdsSysConfig("进销存管理参数", "是否支持按箱码订货");
  sysConfig.value.isStrict = await getRdsSysConfig("供应链管理参数", "补货申请单门店补货量大于配送中心库存量是否严格控制");
  sysConfig.value.inputType = await getRdsSysConfig("供应链管理参数", "商品件数零数录入方式") || '1';
}

// 扫码
const clickScanRight = (type) => {
  uni.scanCode({
    success: async function (res) {
      if (res.result != '' && res.result != undefined && res.result != null) {
        searchText.value = res.result;
        await searchConfirm({
          value: res.result
        });
      }
    }
  });
}

// 校验生效日期
const effectDaChanged = (value) => {
  let nowDate = formatNow('YYYY-MM-DD');
  if (value < nowDate) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '期望送货日期不能小于今天,请检查！'
    })
    setTimeout(() => {
      mainData.value.c_expect_dt = nowDate;
    },200)
    return;
  }
}

const validateDetail = async (args) => {
  const { type, fieldName, oldValue, newValue, itemIndex } = args;
  let result = null;
  let weightUnits;

  switch (fieldName) {
    case 'c_n_pack':
      currentGds.value.c_n_pack = parseInt(newValue);
      currentGds.value.c_n = parseFloat((currentGds.value.c_n_pack * currentGds.value.c_req_pack + Number(currentGds.value.c_n_odd)).toFixed(2));
      currentGds.value.c_n_input = round(currentGds.value.c_n / currentGds.value.c_req_pack, 3);
      calcRowAmount(currentGds.value);
      break;
    case 'c_n_odd':
      currentGds.value.c_n_odd = newValue;
      const n_odd = newValue;
      weightUnits = await getWeightUnits();
      if (!weightUnits.includes(currentGds.value.c_req_unit)) {
        if (n_odd % 1 > 0) {
          uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '本商品数量不允许录入小数，仅重量单位商品可以录入小数'
          });
          setTimeout(() => {
            cardNOddInput.value.getFocus();
          }, 300);
          return;
        }
      }
      const validateResult = validateOddLot(newValue, currentGds.value.c_n_pack, currentGds.value.c_req_pack, currentGds.value.c_unpack);
      result = validateResult.result;
      if (!result || result?.validated) {
        currentGds.value.c_n = validateResult.n;
        currentGds.value.c_n_pack = validateResult.npack;
        currentGds.value.c_n_odd = validateResult.result?.retValue.toFixed('3') || 0;
        currentGds.value.c_n_input = round(currentGds.value.c_n / currentGds.value.c_req_pack, 3);
        calcRowAmount(currentGds.value);
      } else {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: result?.message
        });
        setTimeout(() => {
          // currentGds.value.c_n_odd = oldValue;
          cardNOddInput.value.getFocus();
        }, 300);
      }
      break;
    case 'c_n_input':
      const c_n_odd = round(newValue * currentGds.value.c_req_pack, 3);
      const vResult = validateOddLot(c_n_odd, currentGds.value.c_n_pack, currentGds.value.c_req_pack, currentGds.value.c_unpack, true);
      result = vResult.result;
      if (!result || result?.validated) {
          weightUnits = await getWeightUnits();
          // 在赋值之前判断零数是否为小数
          if (!weightUnits.includes(currentGds.value.c_req_unit) && result?.retValue % 1 > 0) {
              uni.showToast({
                  duration: 2000,
                  icon: 'none',
                  title: '本商品的包装零数不允许为小数，仅重量单位商品的零数允许为小数'
              });
              setTimeout(() => {
                  cardNIptInput.value.getFocus();
              }, 300);
              return;
          }
        currentGds.value.c_n = vResult.n;
        currentGds.value.c_n_pack = vResult.npack;
        currentGds.value.c_n_input = newValue;
        if (result) {
          currentGds.value.c_n_odd = result.retValue;
        }
        calcRowAmount(currentGds.value);
      }
      break;
    case 'c_n_free':
      if (!newValue) {
        currentGds.value.c_n_free = 0;
      }
      break;
  }
}

// 验证零数
const validateNOdd = async () => {
  const weightUnits = await getWeightUnits();
  if (!weightUnits.includes(currentGds.value.c_req_unit)) {
    if (currentGds.value.c_n_odd % 1 > 0 || currentGds.value.c_n_input % 1 > 0) {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: '本商品数量不允许录入小数，仅重量单位商品可以录入小数'
      });
      setTimeout(() => {
        if (sysConfig.value.inputType === '1') {
          cardNOddInput.value.getFocus();
        } else {
          cardNIptInput.value.getFocus();
        }
      }, 300);
      return false;
    }
  }
  const validateResult = validateOddLot(currentGds.value.c_n_odd, currentGds.value.c_n_pack, currentGds.value.c_req_pack, currentGds.value.c_unpack);
  const result = validateResult.result;
  if (!result || result?.validated) {
    currentGds.value.c_n = validateResult.n;
    currentGds.value.c_n_pack = validateResult.npack;
    currentGds.value.c_n_odd = validateResult.result?.retValue.toFixed('3') || 0;
    currentGds.value.c_n_input = round(currentGds.value.c_n / currentGds.value.c_req_pack, 3);
    calcRowAmount(currentGds.value);
    return true;
  } else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: result?.message
    });
    setTimeout(() => {
      if (sysConfig.value.inputType === '1') {
        cardNOddInput.value.getFocus();
      } else {
        cardNIptInput.value.getFocus();
      }
    }, 300);
    return false;
  }
};

const buttonClick = async (t) => {
  const { loginInfo } = mainStore;
  let { singleTag } = t;
  switch (singleTag) {
    case '保存':
      // 保存
      if (detailData.value.length <= 0) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '商品不能为空！'
        });
        return;
      }
      service.enjoyShowLoading('正在保存...');
      await saveBill();
      await billQuery();
      service.enjoyHideLoading();
      break;
    case '审核':
      // 审核
      if (detailData.value.length <= 0) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '商品不能为空！'
        });
        return;
      }
      await saveBill();
      const req = {
        BillId: mainData.value.c_id,
        UserNo: loginInfo.sUser,
        StoreId: mainData.value.c_store_id,
      }
      if (mainData.value.c_status == '0') {
        uni.showModal({
          title: ' 提示',
          content: '请确认，审核单据[' + req.BillId + ']?',
          showCancel: true,
          success: async (res) => {
            if (res.confirm) {
              service.enjoyShowLoading('正在审核...');
              const result = await rdsRequestAsync(rdsUrl.scApi, '商品补货申请单', 'EnjoyBillAudit', req, '501');
              if (result.HasException) {
                uni.showToast({
                  duration: 2000,
                  icon: 'none',
                  title: result.Exception.Message
                });
              }
              await billQuery('审核');
              service.enjoyHideLoading();
            }
          }
        });
      }
      break;
    case '关闭':
      gdsPopup.value.close();
      if (RdsSearchBar.value) {
        RdsSearchBar.value.clear();
      }
      break;
    case '确认':
      if (mainData.value.c_req_priv === '1') {
        if (['2', '3', '5'].includes(currentGds.value.c_d_type) && !currentGds.value.c_dc_store_id) {
          uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '物流模式为直配、配送或直送转直配时，配送中心不能为空！'
          });
          return;
        }
      }
      const result = await validateNOdd();
      if (!result) {
        return;
      }

      if (sysConfig.value.isStrict == '1' && currentGds.value.c_n > currentGds.value.c_n_inv_dc && currentGds.value.c_d_type == '3') {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: `申请数量[${currentGds.value.c_n}]大于配送中心库存数量[${currentGds.value.c_n_inv_dc}]，请检查！`
        });
        setTimeout(() => {
          cardNOddInput.value.getFocus();
        }, 300);
        return;
      }

      if (sysConfig.value.isStrict == '2' && currentGds.value.c_n > currentGds.value.c_n_inv_dc && currentGds.value.c_d_type == '3') {
        var flag = await enjoyConfirm(`申请数量[${currentGds.value.c_n}]大于配送中心库存数量[${currentGds.value.c_n_inv_dc}]，是否继续？`);
        if (!flag) {
          return;
        }
      }

      service.enjoyShowLoading("正在加载...");
      currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
      detailData.value[currentGdsIndex.value] = currentGds.value;
      service.enjoyHideLoading();
      setTimeout(() => {
        listManager.value = detailData.value;
        gdsPopup.value.close();
        if (RdsSearchBar.value) {
          RdsSearchBar.value.clear();
        }
        calcMainAmount();
      }, 300);
      break;
  }
}

const trigger = (e) => {
  if (!mainData.value.c_id) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '单据号不能为空！'
    });
    return false;
  }
  const { loginInfo } = mainStore;
  const req = {
    BillId: mainData.value.c_id,
    UserNo: loginInfo.sUser,
  }
  switch (e.item.text) {
    case '删除单据':
      if (mainData.value.c_status == "0") {
        uni.showModal({
          title: ' 提示',
          content: '请确认，删除单据[' + req.BillId + ']?',
          showCancel: true,
          success: async (res) => {
            if (res.confirm) {
              service.enjoyShowLoading('正在删除...');
              const result = await rdsRequest(rdsUrl.scApi, '商品补货申请单', 'EnjoyBillDelete', req, '501');
              service.enjoyHideLoading();
              uni.showToast({
                duration: 3500,
                icon: 'none',
                title: '操作成功'
              });
              uni.redirectTo({
                url: './index'
              });
            }
          }
        });
      }
      break;
  }
}

// 保存数据
const saveBill = async () => {
  if (detailData.value.length <= 0) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '请录入商品！'
    });
    return;
  }
  const flag = mainData.value.c_id;
  let reqBillId = mainData.value.c_id;
  if (!flag) {
    const getBilllIdReq = {
      BillIdKeyValue: {
        key: "c_id",
        value: ""
      },
      BillVariable: "",
      TableName: "tb_po_req",
      BillName: "商品补货申请单"
    }
    const billlId = await rdsRequest(rdsUrl.mainApi, '单号生成服务', 'EnjoyGetBillId', getBilllIdReq, '501');
    if (billlId) {
      mainData.value.c_mk_userno = sUser.value;
      mainData.value.c_mk_store_id = sUserStore.value;
      reqBillId = billlId;
    }
  } else {
    mainData.value.c_req_userno = sUser.value;
    mainData.value.c_modify_userno = sUser.value;
    mainData.value.c_modify_dt = dateRangUtil.formatDate(new Date(),'YYYY-MM-DD HH:mm:ss');
  }
  let listData = {
    ...mainData.value,
    c_id: reqBillId,
  };

  detailData.value.forEach(x => x.c_id = reqBillId)
  newList = detailData.value.filter(x => x.rowType == 1 || !x.hasOwnProperty('rowType'));
  modifiedList = detailData.value.filter(x => x.rowType == 2);
  const req = {
    NewList: flag ? [] : [listData],
    ModifiedList: flag ? [listData] : [],
    DelList: [],
    TableName: "tb_po_req",
    PrimaryKeys: ["c_tenant_id", "c_id"],
    ChildData: [{
      ChildTableName: "tb_po_req_g",
      ParentTableName: "tb_po_req",
      ChildColumnNames: ["c_id"],
      ParentColumnNames: ["c_id"],
      ChildSaveModel: {
        NewList: newList,
        ModifiedList: modifiedList,
        DelList: delList,
        TableName: "tb_po_req_g",
        PrimaryKeys: ["c_tenant_id", "c_id", "c_gsort"],
      },
    }],
    BillSet: {
      BillIdKeyValue: {
        key: "c_id",
        value: reqBillId
      },
      BillVariable: "",
      TableName: "tb_po_req",
      BillName: "商品补货申请单"
    },
  };
  const result = await rdsRequest(rdsUrl.scApi, '商品补货申请单', 'EnjoyBillSaveNew', req, '501');
  if (result && result.BillId) {
    mainData.value.c_id = reqBillId;
    title.value = reqBillId;
  }
  uni.showToast({
    duration: 2000,
    icon: 'none',
    title: `保存成功`
  });
  newList = [];
  modifiedList = [];
  delList = [];
}

const setClass = async (itemIndex) => {
  isCurrentGds.value = Array(isCurrentGds.value.length).fill(false);
  isCurrentGds.value[itemIndex] = true;
}

const palKindInput = (value) => {
  mainData.value.c_pal_kind = value;
}

// 获取单据详情信息
const billQuery = async (type) => {
  if (!mainData.value.c_id) {
    return;
  }
  service.enjoyShowLoading('正在加载...');
  const req = {
    BillId: mainData.value.c_id,
  };
  const result = await rdsRequest(rdsUrl.scApi, '商品补货申请单', 'EnjoyBillQuery', req, '501');
  if (result.ds.length > 0) {
    mainData.value = result.ds[0];
    detailData.value = result.ds1;
    detailData.value.forEach(x => {
      x.rowType = 0;
    })
    title.value = mainData.value.c_id + '详情';
    c_sku_rec.value = detailData.value.length || 0;
    c_n_rec.value = detailData.value.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
  } else {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: '未查询到数据',
      mask: true,
    });
  }
}

const searchConfirm = async (e) => {
  if (!e || !e.value) {
    return;
  }
  let searchValue = e.value;
  const punctuationRegex = /[\u4e00-\u9fa5]|[。，“”‘’：；？！]|[!\"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/;
  if (punctuationRegex.test(searchValue)) {
    uni.showToast({
      title: '输入的商品条码或编码有误，请检查！',
      icon: 'none',
      duration: 3500,
    });
    return;
  }
  if (!mainData.value.c_adno) {
    uni.showToast({
      title: '请先选择部门!',
      icon: 'none',
      duration: 2000,
    });
    setTimeout(() => {
      clickRight('c_adno')
    }, 1000);
    return;
  }
  if (!mainData.value.c_store_id) {
    uni.showToast({
      title: '请先选择机构!',
      icon: 'none',
      duration: 2000,
    });
    setTimeout(() => {
      clickRight('c_store_id')
    }, 1000);
    return;
  }
  let barCode = '';
  if (searchValue.length == 7) {
    const gdsInfo = await getGdsInfo(searchValue);
    barCode = gdsInfo && gdsInfo.c_barcode ? gdsInfo.c_barcode : searchValue;
  } else {
    barCode = searchValue;
  }
  searchText.value = searchValue;
  const itemIndex = detailData.value.findIndex(i => i.c_barcode == barCode);
  if (itemIndex !== -1) {
    service.enjoyShowLoading('正在加载...');
    // //计算当前商品所在页数
    // const page = Math.ceil(itemIndex / 10);
    // //如果商品所在页数大于当前页数，刷新到当前页数
    // if (this.currentPage < page) {
    //   this.currentPage = page;
    //   this.$refs.paging.refreshToPage(Math.ceil(itemIndex / 10));
    // }
    // setTimeout(() => {
    //   //定位到当前商品
    //   this.$refs.paging.scrollIntoViewById(`item-${itemIndex}`, 300, true);
    // }, 300);
    onClickGdsInfo(detailData.value[itemIndex], itemIndex)
    service.enjoyHideLoading();
  } else {
    if (mainData.value.c_status != '0') {
      const itemIndex = detailData.value.findIndex(i => i.c_barcode == barCode);
      if (itemIndex !== -1) {
        // service.enjoyShowLoading('正在加载...');
        // //计算当前商品所在页数
        // const page = Math.ceil(itemIndex / 10);
        // //如果商品所在页数大于当前页数，刷新到当前页数
        // if (this.currentPage < page) {
        //   this.currentPage = page;
        //   this.$refs.paging.refreshToPage(Math.ceil(itemIndex / 10));
        // }
        // setTimeout(() => {
        //   //定位到当前商品
        //   this.$refs.paging.scrollIntoViewById(`item-${itemIndex}`, 300, true);
        // }, 300);
        // service.enjoyHideLoading();
      } else {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '未查询到商品'
        });
      }
      return;
    }
    currentGds.value = initRow();
    let args = { fieldName: 'c_gcode', row: currentGds.value, newValue: searchText.value, };
    service.enjoyShowLoading('正在加载...');
    const result = await validateGds({
      uniqueKey: '商品补货申请单', billType: '501', args,
      head: {
        code: sUserStore.value,
        adno: mainData.value.c_adno,
        login_store: sUserStore.value,
        provider: currentGds.value.c_provider,
        con_no: currentGds.value.c_con_no,
        wno: mainData.value.c_wno,
      },
      listManager: detailData.value,
      mapping: [
        ...defaultMapping,
        //分店信息
        ['c_basic_unit', 'c_basic_unit'],
        ['c_tax_rate', 'c_tax_rate'],
        ['c_type', 'c_type'],
        ['c_unpack', 'c_unpack'],
        ['c_req_pack', 'c_content'],
        ['c_req_unit', 'c_unit'],
        ['c_n_disp', 'c_dnlmt_number'],         //最佳货位量 ，字段不一致
        ['c_dnlmt_day', 'c_dnlmt_day'],         //安全库存天数
        ['c_min_to_order', 'c_n_min_order'],    //补货点，字段不一致
        ['c_n_min', 'c_n_min'],
        ['c_n_max', 'c_n_max'],
        //采购信息
        ['c_con_no', 'c_con_no'],
        ['c_provider', 'c_provider'],
        ['c_con_type', 'c_con_type'],
        ['c_pt_in', 'c_pt_in'],
        ['c_pt_pay', 'c_pt_pay'],
        ['c_pt_pay_con', 'c_pt_pay_con'],
        ['c_pet_pay', 'c_pet_pay'],
        ['c_pt_type', 'c_pt_type'],
        ['c_disc_rate', 'c_disc_rate'],
        ['c_tax_src', 'c_tax_src'],
        ['c_tax_rate_pay', 'c_tax_rate_pay'],
        ['c_deduct_rate', 'c_deduct_rate'],
        ['c_dc_store_id', 'c_dc_store_id'],
        ['c_dc_wno', 'c_dc_wno'],
        ['c_dc_ret_wno', 'c_dc_ret_wno'],
        ['c_pro_status', 'c_pro_status'],
        ['c_pt_pay_pop', 'c_pro_pt_pay'],      //促销进价（含税）,字段不一致
        ['c_pro_name', 'c_pro_name'],
        ['c_pro_period', 'c_pro_period'],

        ['c_min_order_n', 'c_min_order_n'],     //最小订量
        //合同信息
        ['c_pay_type', 'c_pay_type'],           //结算方式
        //商品分店信息统计信息
        ['c_lastsale_dt', 'c_lastsale_dt'],
        ['c_firstorder_dt', 'c_firstorder_dt'],
        ['c_init_disc', 'c_init_disc'],
        ['c_init_qtty', 'c_init_qtty'],
        ['c_dms', 'c_dms'],
        ['c_pdms', 'c_pdms'],
        ['c_n', ''],                            //c_n是过程up_chk_bill_rule里输出的条码含量，这里需要特殊处理下不要取过程返回的
        ['c_sn_lastweek', 'c_sn_lastweek'],     //TODO:上周销量，没有数据源

        //库存信息
        ['c_n_inv', 'c_n_inv'],                 //TODO:库存数量 没有数据源
        ['c_n_inv_bad', 'c_n_inv_bad'],         //TODO:坏货数量 没有数据源
        ['c_n_onway_in', 'c_n_onway_in'],       //TODO:入库在途数量 没有数据源
        ['c_n_onway_out', 'c_n_onway_out'],     //TODO:出库在途数量 没有数据源
        ['c_sellout_days', 'c_sellout_days'],   //TODO:可销天数=库存数量/DMS 没有数据源
        ['c_n_inv_dc', 'c_ext1'],           //TODO:配送中心库存数量 没有数据源

        //订货参数
        ['c_uplmt_day', 'c_buy_weeks']       //
        //['c_expect_dt', 'c_expect_dt'],
      ],
      initRow: initRow,
      callback: async (items) => {
        items.forEach(item => {
          //期望到货日期
          item.c_expect_dt = todayAdd(item.c_delivery_day)//到货日期=当前日期+到货日
          item.c_pt_pay_con = item.c_pt_pay;
          item.c_pt_type = 'C';//合同价
          //如果促销进价不为零，表示有促销进价
          if (item.c_pro_pt_pay !== 0 && (((item.c_pro_status || '') === '') || item.c_pro_status === '4') &&
              item.c_pro_en_dt >= formatNow('YYYY-MM-DD')) {
            item.c_pt_type = 'P';//P-促销价
            item.c_pt_pay = item.c_pro_pt_pay;
            item.c_pet_pay = item.c_pro_pet_pay;
            item.c_pt_in = item.c_pro_pt_in;
          }
          item.c_disc_rate = item.c_pt_pay / item.c_pt_pay_con * 100;
          if (sysConfig.value.isBarcode == '1' && item.c_n > 1) {
            item.c_content = item.c_n;
            item.c_unit = item.c_b_unit;
            item.c_price = item.c_n * item.c_price;
          }
          // item.c_req_pack = this.sysConfig.isBarcode == '1' && item.c_n > 1 ? item.c_n : item.c_content;
        })
        return true;
      }
    })

    if (result) {
      listManager.value = detailData.value;
      currentGdsIndex.value = detailData.value.findIndex(i => i.c_barcode === barCode);
      onClickGdsInfo(detailData.value[currentGdsIndex.value], currentGdsIndex.value);
      // setTimeout(() => {
      //   //计算当前商品所在页数
      //   const page = Math.ceil(this.currentGdsIndex / 10);
      //   //如果商品所在页数大于当前页数，刷新到当前页数
      //   if (this.currentPage < page) {
      //     this.currentPage = page;
      //     this.$refs.paging.refreshToPage(page);
      //   }
      //   //定位到当前商品
      //   this.$refs.paging.scrollIntoViewById(`item-${this.currentGdsIndex}`, 300, true);
      // }, 300);
    }
    service.enjoyHideLoading();
  }
  c_sku_rec.value = detailData.value.length || 0;
}

const getGdsInfo = async (gcode) => {
  const req = {
    WhereList: [
      { c_col: "c_store_id", c_oper: "等于", c_value: mainData.value.c_store_id, c_logic: "而且" },
      { c_col: "inputOrigMode", c_logic: "而且", c_value: "1", c_oper: "等于" },
      { c_col: "c_gcode", c_oper: "等于", c_value: gcode, c_logic: "而且" }
    ]
  };
  const result = await rdsRequest(rdsUrl.bcApi, '弹窗通用查询', 'FetchComplexGds', req);
  if (result.ReturnObject.length > 0) {
    return result.ReturnObject[0]
  }
};

const getName = (key, value) => {
  if (!value) {
    return ''
  }
  let list = [];
  value.split(',').map(item => {
    list.push("[" + item + "]" + (getRelatedName(key, item) || key));
  })
  return list.join(',');
}

const getSelectList = (key) => {
  return getDictSelect(key);
}

// 计算当前金额
const calcRowAmount = (row) => {
  currentGds.value.c_at_pay = calcAtInByPt({ c_pt: row.c_pt_pay, c_n: row.c_n });
  currentGds.value.c_at_in = calcAtInByPt({ c_pt: row.c_pt_in, c_n: row.c_n });
  currentGds.value.c_aet_pay = calcAtInByPt({ c_pt: row.c_pet_pay, c_n: row.c_n });
  currentGds.value.c_at_sale = calcAtInByPt({ c_pt: row.c_price, c_n: row.c_n });
}

const calcMainAmount = () => {
  mainData.value.c_at_sale = detailData.value.reduce((pre, current) => pre + current.c_at_sale, 0);
  mainData.value.c_at_req = detailData.value.reduce((pre, current) => pre + current.c_at_pay, 0);
  mainData.value.c_at_disc = detailData.value.reduce((pre, current) => pre + round((current.c_pt_pay_con - current.c_pt_pay) * current.c_n, 2), 0);
  //已录入品种数和已录入数量
  c_sku_rec.value = detailData.value.length || 0;
  c_n_rec.value = detailData.value.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
}

const initRow = (index) => {
  const sort = Math.max(0, ...detailData.value.map(f => f.c_gsort)) + 1 + (index || 0);
  return {
    c_tenant_id: '',
    c_id: '',
    c_gsort: sort,
    c_gds_flag: '',
    c_gcode: '',
    c_gname: '',
    c_barcode: '',
    c_type: '',
    c_adno: '',
    c_ccode: '',
    c_bcode: '',
    c_req_unit: '',
    c_req_pack: 0,
    c_tax_src: '',
    c_tax_rate_pay: 0,
    c_tax_rate: 0,
    c_pt_pay_con: 0,
    c_pt_pay_pop: 0,
    c_disc_rate: 0,
    c_pt_pay: 0,
    c_pet_pay: 0,
    c_pt_in: 0,
    c_pt_fall: 0,
    c_pt_type: 'C',//合同价
    c_price: 0,
    c_deduct_rate: 0,
    c_n_advice: 0,
    c_unpack: '',
    c_n_pack: 0,
    c_n_odd: 0,
    c_n_input: 0,
    c_n: 0,
    c_n_free: 0,
    c_at_pay: 0,
    c_aet_pay: 0,
    c_at_in: 0,
    c_at_sale: 0,
    c_provider: '',
    c_con_type: '',
    c_con_no: '',
    c_pay_type: '',
    c_d_type: '',
    c_s_mode: '',
    c_dc_store_id: '',
    c_dc_wno: '',
    c_wno: mainData.value.c_wno,
    // c_wname: this.mainData.c_wname,
    c_cs_mode: '',
    // c_cs_store_id: this.mainData.c_cs_store_id,
    // c_cs_store_name: this.mainData.c_cs_store_name,
    // c_cs_store_name_en: this.mainData.c_cs_store_name_en,
    c_expect_dt: mainData.value.c_expect_dt,
    c_modify_opl_reason: '',
    c_reason: '',
    c_uplmt_day: 0,
    c_dnlmt_day: 0,
    c_n_disp: 0,
    c_plan_dms: 0,
    c_n_min: 0,
    c_n_max: 0,
    c_min_to_order: 0,
    c_min_order_n: 0,
    c_sn_lastweek: 0,
    c_dms: 0,
    c_pdms: 0,
    c_n_inv: 0,
    c_n_inv_bad: 0,
    c_n_onway_in: 0,
    c_n_onway_out: 0,
    c_sellout_days: 0,
    c_n_inv_dc: 0,
    c_pro_status: '',
    c_pro_name: '',
    c_pro_period: '',
    c_src_id: '',
    c_src_type: '',
    c_to_id: '',
    c_to_type: '',
    c_proc_status: '',
    c_fall_reason: '',
    c_note: ''
  }
}

const onClickGdsInfo = (item, index) => {
  service.enjoyShowLoading('正在加载...');
  try {
    currentGdsIndex.value = index;
    currentGds.value = JSON.parse(JSON.stringify(item));
    currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
    gdsPopup.value.open();
    // 自动聚焦有问题 暂时关闭
    // setTimeout(() => {
    //   cardNPackInput.value.getFocus();
    // },500);
  } catch (error) {
    service.enjoyHideLoading();
  }
  service.enjoyHideLoading();
}

// 商品选择部门
const goodsClickRight = async () => {
  clickRight('c_wno_goods')
}

// 选择框点击事件
const clickRight = (type) => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  if (type == 'c_store_id') {
    parms.SelectionType = "机构选择";
    parms.SelectedItems = mainData.value.c_store_id;
  } else if (type == 'c_adno') {
    parms.SelectionType = "部门选择";
    parms.SelectedItems = mainData.value.c_adno;
  } else if (type == 'c_wno') {
    parms.SelectionType = "仓库选择";
    parms.SelectedItems = mainData.value.c_wno;
    parms.SelectionStoreId = sUserStore.value;
    isGoods.value = false;
  } else if (type == 'c_wno_goods') {
    parms.SelectionType = "仓库选择";
    parms.SelectedItems = currentGds.value.c_wno;
    parms.SelectionStoreId = sUserStore.value;
    isGoods.value = true;
  }
  Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (e) =>{
  const { loginInfo } = mainStore;
  if (e.SelectionType=='部门选择') {
    //验证部门层级
    let curAdno = e.BackParms.Key;
    const validateResult = await validateAdnoLevel({ IuputData: curAdno, billKind: "50", tenantId: loginInfo.idsToken.tenantid });
    if (validateResult && validateResult.HasException) {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: validateResult.Exception.Message
      });
      setTimeout(() => {
        clickRight('c_adno')
      }, 1000);
      return;
    }
    const userAdno = await getRdsUserDepartAuthority();
    if (userAdno.includes(curAdno)) {
      mainData.value.c_adno = curAdno;
    } else {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: `没有部门${curAdno}权限！`
      });
      setTimeout(() => {
        clickRight('c_adno')
      }, 1000);
      return
    }
  } else if (e.SelectionType=='机构选择') {
    let curStoreId = e.BackParms.Key;
    const result = await validateStoresAndWno({ value: curStoreId, wno: mainData.value.c_wno });
    if (result) {
      const result = await validateStores(
          { fieldName: 'c_store_id', row: mainData.value, newValue: curStoreId },
          { ischecklimit: true, firstValueMode: true }
      );
      if (['2', '3'].includes(result.c_type)) {
        // 更新机构信息
        sUserStoreName.value = e.BackParms.Value;
        sUserStore.value = curStoreId;
        mainData.value.c_store_id = curStoreId;
        mainData.value.c_mk_store_id = curStoreId;
      } else {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: '请选择分店或配送中心！'
        });
        setTimeout(() => {
          clickRight('c_store_id')
        }, 300);
      }
    } else {
      mainData.value.c_wno = '';
    }
  } else if (e.SelectionType=='仓库选择' && !isGoods.value) {
    mainData.value.c_wno = e.BackParms.Key;
  } else if (e.SelectionType=='仓库选择' && isGoods.value) {
    currentGds.value.c_wno = e.BackParms.Key;
  }
}

const validateMain = async (t, e) => {
  switch (t) {
    case 'c_adno':
      const lsGds = detailData.value.filter(i => i.c_gcode?.length > 0);
      if (lsGds.length > 0 && lsGds.some(i => i.c_adno.startsWith(e) == false)) {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '录入部门与明细商品部门不匹配！'
        });
        return;
      }
      break;
  }
};

const dTypeInput = (value) => {
  if (value != '2') {
    currentGds.value.c_s_mode = '';
  } else {
    currentGds.value.c_s_mode = '1';
  }
  if (['1', '5'].includes(value)) {
    currentGds.value.c_dc_store_id = '';
  }
}

const change = (e) => {
  isOpened.value = e;
}

const bindClick = (e, index) => {
  uni.showModal({
    title: ' 提示',
    content: '您确定要删除数据吗？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        delList.push(detailData.value[index]);
        detailData.value.splice(index, 1);
        listManager.value = detailData.value;
        calcMainAmount();
      }
    }
  });
}

const enjoyConfirm = async(e) => {
  return new Promise((resolve) => {
    uni.showModal({
      title: '提示',
      content: e,
      success: (res) => {
        if (res.confirm) {
          resolve(true);
        } else {
          resolve(false);
        }
      }
    });
  });
}

// 审批
const approve = (req) => {
  if (mainData.value.c_approve_status == "1") {
    uni.showModal({
      title: ' 提示',
      content: '请确认，单据[' + req.BillId + ']发起审批?',
      showCancel: true,
      success: async (res) => {
        if (res.confirm) {
          await sendApprove();
        }
      }
    });
  } else {
    const { loginInfo } = mainStore;
    const item = {
      c_approve_status: mainData.value.c_approve_status,
      Id: mainData.value.c_id,
      UserNo: loginInfo.sUser,
      StoreId: mainData.value.c_store_id,
      AppParam: '损溢申请单',
    }
    const request = {
      Id: req.BillId,
      UserNo: loginInfo.sUser,
      StoreId: mainData.value.c_store_id,
    }
    // apps.ApprovePath(request, item, res => { }, res => { });
  }
}

const sendApprove = async () => {
  const { loginInfo } = mainStore;
  const ApproveBills = {
    AppPage: "/modules/ic/oper/lossReq/list",
    AppParam: "损溢申请单",
    AppUsers: [],
    BillId: mainData.value.c_id,
    BillKey: mainData.value.c_id,
    BillRealType: "损溢申请单",
    BillType: "损溢申请单",
    CFGName: "损溢申请单",
    FlowGuid: "e41e4780-fb44-407f-9757-95074e1ee46b",
    FlowName: "损溢申请单",
    HtmlContent: "",
    HtmlMobileContent: "",
    IsMainFlow: true,
    IsCanTempApp: false,
    IsSelected: true,
    IsTempApp: false,
    MdCode: "rds_ic_po_pal",
    NoticType: "",
    ProjectName: "RDS", // OA\RMIS\RMISNew,
    StoreId: mainData.value.c_store_id,
    AppReqUserNo: loginInfo.sUser,
    UserNo: loginInfo.sUser,
    TempTitle: `单据:${mainData.value.c_id}`,
    // ApproveServiceUrl: Url.EnjoyRMIS,
  }
  const approveResult = await rdsRequest(rdsUrl.apiApi, '审批处理', 'SendApprove', ApproveBills, '501');
  if (approveResult.Result) {
    await billQuery('审批');
  }
}

</script>

<style lang="scss" scoped>
@import '../../../main.scss';
.top-view {
  width: 100%;
  height: 88rpx;
}
.extra-view {
  margin-right: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60rpx;
  height: 100%;
}
.footer-view {
  width: 100%;
  flex: 1;
}
.list-scroll {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.bottom-view {
  width: 100%;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
}
.center-style {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20rpx;
  //gap: 20rpx;
}
.gap-view {
  width: 20rpx;
  height: auto;
}
//内容行
.item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  margin-top: 16rpx;
  row-gap: 8rpx;
}
.line-view {
  width: 100%;
  height: 1rpx;
  background: #EEEEEE;
  margin: 20rpx 0;
}
.popup-content {
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0;
  width: 100%;
  background-color: #ffffff;
}
.popup-bottom {
  background: #ffffff;
  border-top: 1rpx solid $uni-line-color;
  display: flex;
  justify-content: center;
  padding: 20rpx;
}
</style>
